﻿using System;
using System.Collections.Generic;

namespace Flagwind.Externals.Redis.Commands
{
	[Flagwind.Services.CommandOption("not", Description = "${Text.SetCommand.NotExists}")]
	[Flagwind.Services.CommandOption("duration", Type = typeof(TimeSpan), Description = "${Text.SetCommand.Duration}")]
	public class SetCommand : RedisCommandBase
	{
		#region 构造方法

		public SetCommand() : base("Set")
		{
		}

		public SetCommand(IRedisService redis) : base(redis, "Set")
		{
		}

		#endregion

		#region 执行方法

		protected override object OnExecute(Services.CommandContext context)
		{
			if(context.Expression.Arguments.Length == 0)
				throw new Flagwind.Services.CommandException("Missing arguments.");

			if(context.Expression.Options.Contains("duration") && context.Expression.Options.Contains("expires"))
				throw new Flagwind.Services.CommandOptionException("duration, expires");

			TimeSpan duration = context.Expression.Options.GetValue<TimeSpan>("duration");
			var notExists = context.Expression.Options.Contains("not") || context.Expression.Options.Contains("notExists");

			if(context.Expression.Arguments.Length == 1)
			{
				if(context.Parameter != null)
					return this.Redis.GetCache(null).SetValue(context.Expression.Arguments[0], context.Parameter, duration, notExists);

				throw new Flagwind.Services.CommandException("Missing arguments.");
			}

			return this.Redis.SetValue(context.Expression.Arguments[0], context.Expression.Arguments[1], duration, notExists);
		}

		#endregion
	}
}